<template>

  <div class="consultation-detail">
    <!-- 顶部导航 -->
    <van-nav-bar
        title="问诊详情"
        left-text="返回"
        left-arrow
        @click-left="onBack"
        fixed
    />

    <!-- 患者信息卡片 -->
    <div class="patient-card">
      <van-cell-group inset>
        <van-cell center>
          <template #icon>
            <van-image
                round
                width="40"
                height="40"
                :src="detail.userAvatar || '/avatar-default.png'"
                style="margin-right: 8px"
            />

          </template>
          <template #title>
            <span class="patient-name">{{ detail.realName }}</span>
            <van-tag :type="getStatusType(detail.status)" style="margin-left: 8px">
              {{ getStatusText(detail.status) }}
            </van-tag>
          </template>
          <template #label>
            <div class="patient-info">
              <span>{{ detail.gender === 1 ? '男' : '女' }}</span>
              <span style="margin: 0 8px">|</span>
              <span>{{ detail.age }}岁</span>

            </div>
          </template>
        </van-cell>
      </van-cell-group>

    </div>

    <!-- 问诊内容 -->

    <!--    <div class="consultation-content">-->

    <!--      <van-cell-group inset>-->

    <!--        <van-cell title="病情描述" >-->

    <!--          <template #label>-->

    <!--            <div class="description">{{ detail.description  || '暂无描述'}}</div>-->

    <!--          </template>-->

    <!--        </van-cell>-->

    <!--      </van-cell-group>-->

    <!--    </div>-->


    <!-- 聊天记录 -->

    <div class="chat-container" ref="chatContainer">
      <div class="chat-list">
        <template v-for="msg in messages" :key="msg.id">
          <!-- 系统消息 -->
          <div v-if="msg.type === 'system'" class="system-message">
            {{ msg.content }}
          </div>
          <!-- 聊天消息 -->
          <div
              v-else
              class="message"
              :class="isCurrentUserMessage(msg.type) ? 'message-right' : 'message-left'"
          >
            <van-image
                round
                width="40"
                height="40"
                :src="isCurrentUserMessage(msg.type) ? detail.doctorAvatar : detail.userAvatar"
            />
            <div class="message-content">
              <div class="message-text">{{ msg.content }}</div>
              <div class="message-time">{{ formatTime(msg.createTime) }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>


    <!-- 底部操作栏 -->
    <div class="action-bar">
      <template v-if="detail.status === 0">
        <van-button type="primary" block @click="handleAccept">接受问诊</van-button>
        <van-button type="danger" block @click="handleReject">拒绝问诊</van-button>
      </template>
      <template v-else-if="detail.status === 1">
        <van-field
            v-model="message"
            placeholder="请输入消息"
            :disabled="!isOnline"
        >
          <template #button>
            <van-button
                size="small"
                type="primary"
                @click="handleSend"
                :disabled="!message.trim() || !isOnline"
            >
              发送
            </van-button>
          </template>
        </van-field>
        <van-button
            type="warning"
            block
            @click="showEndDialog = true"
            style="margin-top: 8px"
        >
          结束问诊
        </van-button>
      </template>
    </div>


    <!-- 结束问诊弹窗 -->
    <van-dialog
        v-model:show="showEndDialog"
        title="结束问诊"
        show-cancel-button
        @confirm="handleEnd"
    >
      <van-field
          v-model="diagnosis"
          label="诊断意见"
          type="textarea"
          placeholder="请输入诊断意见"
          rows="3"
          maxlength="500"
          show-word-limit
      />

    </van-dialog>
  </div>
</template>


<script setup>

import {ref, onMounted, onUnmounted, nextTick} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useUserStore} from '@/stores/user'
import {showSuccessToast, showFailToast, showConfirmDialog} from 'vant'

import router from '@/router'

import {
  getConsultationDetail,
  acceptConsultation,
  rejectConsultation,
  endConsultation,
  sendConsultationMessage

} from '@/api/doctor'


import dayjs from 'dayjs'


const route = useRoute()
// const router = useRouter()
const userStore = useUserStore()
const consultationId = route.params.id
const doctorId = userStore.userId
const isOnline = ref(userStore.userInfo.online)
const detail = ref({})
const messages = ref([])
const message = ref('')
const diagnosis = ref('')
const showEndDialog = ref(false)
const chatContainer = ref(null)
// 获取问诊详情
const loadDetail = async () => {
  try {
    const {data} = await getConsultationDetail(consultationId)
    detail.value = data
    messages.value = data.messages || []
    scrollToBottom()
  } catch (error) {
    showFailToast('获取问诊详情失败')
  }
}


// 接受问诊
const handleAccept = async () => {
  try {
    await acceptConsultation(consultationId)
    showSuccessToast('已接受问诊')
    detail.value.status = 1
    loadDetail() // 重新加载问诊详情

  } catch (error) {
    showFailToast('接受问诊失败')
  }
}

// 拒绝问诊
const handleReject = async () => {
  try {
    await showConfirmDialog({
      title: '提示',
      message: '确认拒绝此次问诊吗？',
    })
    await rejectConsultation(consultationId)
    showSuccessToast('已拒绝问诊')
    router.push('/doctor/consultation')
  } catch (error) {
    if (error.cancel) return
    showFailToast('拒绝问诊失败')
  }
}

// 发送消息
const handleSend = async () => {
  if (!message.value.trim()) return
  const msgData = {
    consultationId: consultationId,
    fromId: doctorId,
    toId: detail.value.userId,
    content: message.value,
    type: 'doctor' // 标识消息来源
  }

  try {
    // 先保存消息到数据库
    await sendConsultationMessage(msgData)
    showSuccessToast('消息发送成功')

    // 清空消息框
    message.value = ''

    // 重新获取消息
    messages.value = await getConsultationDetail(consultationId).then(res => res.data.messages)

    // detail.value = data
    scrollToBottom()
  } catch (error) {
    showFailToast('发送失败')
  }
}

// 结束问诊
const handleEnd = async () => {

  if (!diagnosis.value.trim()) {
    showFailToast('请输入诊断意见')
    return
  }

  try {
    await endConsultation(consultationId, diagnosis.value)
    showSuccessToast('问诊已结束')


    router.push('/doctor/consultation')

    // router.push('/doctor/consultation')
  } catch (error) {
    showFailToast('结束问诊失败')
  }
}


// 滚动到底部

const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}


// 返回上一页

const onBack = () => {
  // router.push('/doctor/consultation')
  router.push('/doctor/consultation');
}


// 格式化时间

const formatTime = (time) => {
  return dayjs(time).format('HH:mm')
}


// 获取状态文本

const getStatusText = (status) => {
  const statusMap = {
    0: '待接诊',
    1: '问诊中',
    2: '已完成',
    3: '已取消'
  }
  return statusMap[status] || '未知状态'
}


// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'danger'
  }
  return typeMap[status] || 'default'
}

// 判断是否为当前用户的消息
const isCurrentUserMessage = (type) => {
  return type === 'doctor'

}


onMounted(() => {
  loadDetail()
})


</script>


<style lang="scss" scoped>

.consultation-detail {

  min-height: 100vh;

  background-color: #f7f8fa;

  padding: 46px 0 60px;


  .patient-card {

    margin: 12px;

  }


  .consultation-content {

    margin: 12px;


    .description {

      font-size: 14px;

      color: #666;

      line-height: 1.5;

      white-space: pre-wrap;

    }

  }


  .chat-container {

    margin: 12px;

    padding: 12px;

    background-color: #fff;

    border-radius: 8px;

    height: calc(100vh - 300px);

    overflow-y: auto;


    .system-message {

      text-align: center;

      color: #999;

      font-size: 12px;

      margin: 8px 0;

    }


    .message {

      display: flex;

      margin-bottom: 16px;


      .message-content {

        max-width: 70%;

        margin: 0 12px;


        .message-text {

          padding: 12px;

          border-radius: 8px;

          font-size: 14px;

          word-break: break-all;

        }


        .message-time {

          font-size: 12px;

          color: #999;

          margin-top: 4px;

        }

      }


      &.message-left {

        .message-content .message-text {

          background-color: #fff;

          border: 1px solid #eee;

        }

      }


      &.message-right {

        flex-direction: row-reverse;


        .message-content {

          .message-text {

            background-color: #1989fa;

            color: #fff;

          }

          .message-time {

            text-align: right;

          }

        }

      }

    }

  }


  .action-bar {

    //position: fixed;

    bottom: 0;

    left: 0;

    right: 0;

    background-color: #fff;

    padding: 8px 12px;

    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);


    .van-button {

      margin-bottom: 8px;


      &:last-child {

        margin-bottom: 0;

      }

    }

  }

}

</style>
